<?php

namespace app\admin\controller\api;

use app\admin\service\FeiShuService;
use app\admin\service\WxWorkOAuthService;
use think\admin\Controller;
use think\facade\Log;

/**
 * 飞书回调管理
 * Class FeiShu
 * @package app\admin\controller\api
 */
class FeiShu extends Controller
{
    /**
     * 回调地址: admin/api.FeiShu/server(https://feishu.szyoukejia.com/admin/api/feishu/server)
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function server()
    {
        $server = FeiShuService::instance()->server();
        $message = $server->getMessage();

        Log::info('事件消息: ', $message);

        if (isset($message['challenge'])) {
            echo json_encode(['challenge' => $message['challenge']]);
            exit();
        }

        switch ($message['header']['event_type'] ?? '') {
            case 'im.message.receive_v1';
                $this->im($message);
                break;

            // 部门操作
            case 'contact.department.created_v3';
            case 'contact.department.deleted_v3';
            case 'contact.department.updated_v3';
                FeiShuService::instance()->departmentList();
                break;

            // 人员操作
            case 'contact.user.created_v3';
            case 'contact.user.updated_v3';
                $userInfo = $message['event']['object'] ?? [];
                FeiShuService::instance()->updateUser($userInfo);
                break;

            // 人员删除
            case 'contact.user.deleted_v3';
                FeiShuService::instance()->deleteUser($message['event']['object']['open_id'] ?? '');
                break;

            default:
                break;
        }
        echo 'success';
    }

    /**
     * 消息回调处理
     * @param $message
     * @return void
     */
    protected function im($message)
    {
        switch ($message['event']['message']['chat_type'] ?? '') {
            case 'group':
                // 群聊消息
                $insertData = [
                    'event_id' => $message['header']['event_id'] ?? '',
                    'event_type' => $message['header']['event_type'] ?? '',
                    'event_create_time' => $message['header']['create_time'] ?? '',
                    'app_id' => $message['header']['app_id'] ?? '',
                    'sender_user_id' => $message['event']['sender']['user_id'] ?? '',
                    'sender_union_id' => $message['event']['sender']['union_id'] ?? '',
                    'sender_open_id' => $message['event']['sender']['open_id'] ?? '',
                    'message_id' => $message['event']['message']['message_id'] ?? '',
                    'chat_id' => $message['event']['message']['chat_id'] ?? '',
                    'root_id' => $message['event']['message']['root_id'] ?? '',
                    'parent_id' => $message['event']['message']['parent_id'] ?? '',
                    'create_time' => $message['event']['message']['create_time'] ?? '',
                    'update_time' => $message['event']['message']['update_time'] ?? '',
                    'thread_id' => $message['event']['message']['thread_id'] ?? '',
                    'message_type' => $message['event']['message']['message_type'] ?? '',
                    'content' => $message['event']['message']['content'] ?? '',
                    'mentions' => isset($message['event']['message']['mentions']) ? json_encode($message['event']['message']['mentions'], JSON_UNESCAPED_UNICODE) : '',
                ];
                $this->app->db->name('message_group')->insert($insertData);

                break;
            case 'p2p':
                // 单聊消息
                $insertData = [
                    'event_id' => $message['header']['event_id'] ?? '',
                    'event_type' => $message['header']['event_type'] ?? '',
                    'event_create_time' => $message['header']['create_time'] ?? '',
                    'app_id' => $message['header']['app_id'] ?? '',
                    'sender_user_id' => $message['event']['sender']['user_id'] ?? '',
                    'sender_union_id' => $message['event']['sender']['union_id'] ?? '',
                    'sender_open_id' => $message['event']['sender']['open_id'] ?? '',
                    'message_id' => $message['event']['message']['message_id'] ?? '',
                    'chat_id' => $message['event']['message']['chat_id'] ?? '',
                    'root_id' => $message['event']['message']['root_id'] ?? '',
                    'parent_id' => $message['event']['message']['parent_id'] ?? '',
                    'create_time' => $message['event']['message']['create_time'] ?? '',
                    'update_time' => $message['event']['message']['update_time'] ?? '',
                    'thread_id' => $message['event']['message']['thread_id'] ?? '',
                    'message_type' => $message['event']['message']['message_type'] ?? '',
                    'content' => $message['event']['message']['content'] ?? '',
                    'mentions' => isset($message['event']['message']['mentions']) ? json_encode($message['event']['message']['mentions'], JSON_UNESCAPED_UNICODE) : '',
                ];
                $this->app->db->name('message_p2p')->insert($insertData);
                break;
            default:
                Log::error('未知消息类型', $message);
                break;
        }
    }

    /**
     * 授权登录回调
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function oauthCallback()
    {
        $openId = FeiShuService::instance()->getOpenId();

        if (empty($openId)) {
            $this->error('无法获取到openid');
        }

        $user = $this->app->db->name('WorkUser')->where('open_id', $openId)->order('id desc')->find();
        if (empty($user)) {
            $this->error('查无该员工!');
        }
        $db = $this->app->db->name('SystemAuth')->field('id')->where(['status' => 1])->whereIn('id', str2arr($user['authorize']));
        $user['nodes'] = array_unique($this->app->db->name('SystemAuthNode')->whereRaw("auth in {$db->buildSql()}")->column('node'));
        $this->app->session->set('user', $user);
        $this->app->db->name('WorkUser')->where(['id' => $user['id']])->update([
            'login_ip'  => $this->app->request->ip(),
            'login_at'  => $this->app->db->raw('now()'),
            'login_num' => $this->app->db->raw('login_num+1'),
        ]);
        sysoplog('飞信用户登录', '登录系统后台成功');

        $callback = urldecode($this->request->get('callback'));

        header("Location: {$callback}");
    }
}

